<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission._delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button
          type="text"
          icon="el-icon-circle-plus-outline"
          size="small"
          @click.stop="handleAddTags(scope.row,scope.index)">标签
        </el-button>
      </template>
    </avue-crud>
    <el-dialog title="用户标签" append-to-body :visible.sync="box" width="1000px">
      <div class="flex gap-2">
        <el-tag
          v-for="tag in this.dynamicTags"
          :key="tag"
          closable
          effect="plain"
          type="success"
          :disable-transitions="false"
          @close="handleClose(tag)">{{ tag }} &nbsp;
        </el-tag>
        <el-input
          v-if="inputVisible"
          v-model="inputValue"
          class="w-20"
          size="small"
          @keyup.enter="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showInput">
          + New Tag
        </el-button>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="box=false">取 消</el-button>
          <el-button type="primary" @click="handleInputConfirm">确 认</el-button>
        </div>
      </template>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getDetail, add, update, remove, getPage} from "@/api/customer/api-customer";
import {mapGetters} from "vuex";

export default {
  data() {
    return {
      box: false,
      inputVisible: false,
      inputValue: "",
      dynamicTags: ['Tag 1', 'Tag 2', 'Tag 3'],
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        menuWidth: 250,
        column: [
          {
            label: "客户编号",
            prop: "code",
            search: true,
            disabled: true,
            addDisplay: false,
            editDisplay: false,
            rules: [{
              required: false,
              message: "请输入客户编号",
              trigger: "blur"
            }]
          },
          {
            label: "生日",
            prop: "birthday",
            type: "date",
            valueFormat: "yyyy-MM-dd",
            format: "yyyy-MM-dd",
            rules: [{
              required: false,
              message: "请输入生日",
              trigger: "blur"
            }]
          },
          {
            label: "邮箱",
            prop: "email",
            rules: [{
              required: true,
              message: "请输入邮箱",
              trigger: "blur"
            }]
          },
          {
            label: "主键",
            prop: "id",
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            rules: [{
              required: true,
              message: "请输入主键",
              trigger: "blur"
            }]
          },
          {
            label: "证件码",
            prop: "idCard",
            rules: [{
              required: true,
              message: "请输入身份证号码",
              trigger: "blur"
            }]
          },
          {
            label: "客户标签",
            prop: 'label',
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: "客户级别",
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=cus_level_dict",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dataType: "number",
            prop: "levelDict",
            slot: true,
            rules: [{
              required: true,
              message: "请输入机构类型",
              trigger: "blur"
            }]
          },
          {
            label: "手机",
            prop: "mobile",
            rules: [{
              required: true,
              message: "请输入手机",
              trigger: "blur"
            }]
          },
          {
            label: "客户座机",
            prop: "phone",
            rules: [{
              required: true,
              message: "请输入客户座机",
              trigger: "blur"
            }]
          },
          {
            label: "性别",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=sex",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dataType: "number",
            prop: "sex",
            slot: true,
            rules: [{
              required: true,
              message: "请输入机构类型",
              trigger: "blur"
            }]
          },
          {
            label: "状态",
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=cus_status_dict",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dataType: "number",
            prop: "statusDict",
            slot: true,
            rules: [{
              required: true,
              message: "请输入机构类型",
              trigger: "blur"
            }]
          },
          {
            label: "备注",
            prop: "remark",
            type: 'textarea',
            minRows: 3,
            maxRows: 5,
            maxlength: 100,
            span: 24,
            showWordLimit: true
          },
          {
            label: "客户详情",
            prop: "detail",
            type: 'textarea',
            minRows: 3,
            maxRows: 5,
            maxlength: 100,
            span: 24,
            showWordLimit: true
          }
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.punter_add, false),
        viewBtn: this.vaildData(this.permission.punter_view, false),
        delBtn: this.vaildData(this.permission.punter_remove, false),
        editBtn: this.vaildData(this.permission.punter_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    /**
     * 打开 标签的 模态窗口
     * @param row
     */
    handleAddTags(row) {
      this.box = true;
    },
    /**
     * 显示标签输入项
     */
    showInput() {
      this.inputVisible = true
    },
    /**
     * 确认添加
     */
    handleInputConfirm() {
      if (this.inputValue) {
        this.dynamicTags.push(this.inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    /**
     *
     * @param tag
     */
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style scoped>
.flex {
  display: flex;
}

.gap-2 {
  grid-gap: 0.5rem;
  gap: 0.5rem;
}
</style>
